//
//  B_ReleaseTopicVC.m
//  Application
//
//  Created by 薛小刚 on 2018/8/9.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_ReleaseTopicVC.h"
#import "B_ReleaseTopicMainView.h"
#import "B_ReleaseTopicModel.h"
#import "XGPhotoManager.h"
#import "XGDatePicker.h"
#import "B_SelectGoodsVC.h"
#import "B_SelecetGoodslistModel.h"
#import "B_GoodsDetailVC.h"

@interface B_ReleaseTopicVC ()

@property (nonatomic, strong) B_ReleaseTopicMainView * releaseTopic;

@property (nonatomic, strong) B_ReleaseTopicModel * topicModel;

@property (nonatomic, strong) XGPhotoManager * photoManager;

@property (nonatomic, assign)BOOL isBusiness;

@end

@implementation B_ReleaseTopicVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"发布话题"];
    self.view = self.releaseTopic;
    [self getData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (B_ReleaseTopicModel *)topicModel {
    if (!_topicModel) {
        _topicModel = [[B_ReleaseTopicModel alloc] init];
        _topicModel.B_ImageArray = [NSMutableArray array];
        _topicModel.B_GoodsArray = [NSMutableArray array];
    }
    return _topicModel;
}


/**
 TODO:重写导航左侧按钮的点击事件
 */
- (void)leftNavigationAction {
    [super leftNavigationAction];
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 TODO:照片选择器懒加载

 @return 返回照片选择器
 */
- (XGPhotoManager *)photoManager {
    if (!_photoManager) {
        _photoManager = [[XGPhotoManager alloc] init];
    }
    return _photoManager;
}


- (B_ReleaseTopicMainView *)releaseTopic {
    if (!_releaseTopic) {
        WeakSelf(weSelf, self);
        _releaseTopic = [[B_ReleaseTopicMainView alloc] init];
        _releaseTopic.topicModel = self.topicModel;
        _releaseTopic.collectionClicked = ^(NSIndexPath *indexPath) {
            //TODO:判断是哪一个   执行相应的操作  查看大图  或者  添加新图
            HXLog(@"点击的图片");
            
            if (weSelf.topicModel.B_ImageArray.count == indexPath.row) {
                [weSelf alertViewWithTitle:@"请选择" message:@"" buttonsTitles:@[@"相机", @"从相册中选择", @"取消"] action:^(NSInteger index) {
                    if (index == 0) {
                        [weSelf.photoManager openCamereWithController:weSelf withImage:^(UIImage *image) {
                            [weSelf.topicModel.B_ImageArray addObject:image];
                            [weSelf.releaseTopic.tableView reloadData];
                        }];
                    } else if (index == 1) {
                        [weSelf.photoManager openMorePhotosWithController:weSelf maxNum:9 withImage:^(NSArray *imageArr, NSArray *array) {
                            weSelf.topicModel.B_ImageArray = [NSMutableArray arrayWithArray:imageArr];
                            [weSelf.releaseTopic.tableView reloadData];
                        }];
                    }
                }];
            } else {
                
            }
        };
        /// TODO:删除图片
        _releaseTopic.deleteImageAction = ^(NSIndexPath *indexPath) {
            
            [weSelf.photoManager deleteImageWithIndex:indexPath.row];
            [weSelf.topicModel.B_ImageArray removeObjectAtIndex:indexPath.row];
            [weSelf.releaseTopic.tableView reloadData];
            
        };
        
        
        /// TODO:商品详情
        _releaseTopic.didSelectRow = ^(UITableView *tableView, NSIndexPath *indexPath) {
            //TODO:商品的点击事件  查看商品详情
            HXLog(@"查看商品详情");
            B_SelecetGoodslistModel * model = weSelf.topicModel.B_GoodsArray[indexPath.row];
            B_GoodsDetailVC * vc = [[B_GoodsDetailVC alloc] init];
            vc.B_GoodsId = model.id;
            [weSelf pushNextViewController:vc];
        };
        /// TODO:重新上传
        _releaseTopic.tableviewReuploadClicked = ^(NSIndexPath *indexPath) {
            //TODO:重新上传的事件
            HXLog(@"重新上传");
            [weSelf.topicModel.B_GoodsArray removeAllObjects];
            [weSelf.releaseTopic.tableView reloadData];
            B_SelectGoodsVC * vc = [[B_SelectGoodsVC alloc] init];
            vc.selectArray = weSelf.topicModel.B_GoodsArray;
            vc.selectBlock = ^(NSMutableArray *array) {
                ///
                weSelf.topicModel.B_GoodsArray = array;
                [weSelf.releaseTopic.tableView reloadData];
            };
            [weSelf pushNextViewController:vc];
            
        };
        _releaseTopic.addGoodsAction = ^{
            //TODO:添加商品的事件
            HXLog(@"添加新商品");
            B_SelectGoodsVC * vc = [[B_SelectGoodsVC alloc] init];
            vc.selectArray = weSelf.topicModel.B_GoodsArray;
            vc.selectBlock = ^(NSMutableArray *array) {
                ///
                weSelf.topicModel.B_GoodsArray = array;
                [weSelf.releaseTopic.tableView reloadData];
            };
            [weSelf pushNextViewController:vc];
        };
        _releaseTopic.sureAction = ^{
            //TODO:确定按钮的时间
            HXLog(@"发布");
            [weSelf.view endEditing:YES];
            [weSelf submitImage];
            
        };
        
    }
    return _releaseTopic;
}

/**
 TODO:获取用户的状态,如果不是商家是没有添加商品的
 */
- (void)getData {
    WeakSelf(weSelf, self);
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/user/selectUserInfo/%@", getUserId()] parameters:nil isCache:YES succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20010"]) {
            if ([[NSString stringWithFormat:@"%@", data[@"values"][@"businessState"]] isEqualToString:@"2"]) {
                weSelf.releaseTopic.isBusiness = YES;
                weSelf.isBusiness = YES;
            } else {
                weSelf.releaseTopic.isBusiness = NO;
                weSelf.isBusiness = NO;
            }
            [weSelf.releaseTopic.tableView reloadData];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}

/**
 TODO:上传图片
 */
- (void) submitImage {
    
    if (ISNULL(self.topicModel.B_ImageArray)) {
        [KeyWindow makeToast:@"请选择图片"];
        return;
    }
    WeakSelf(weSelf, self);
    [NetworkingManager UploadmoreTaskWithURL:[NSString stringWithFormat:@"%@/yearnfor/inter/topic/addTopicPicture", ServiceIp] imagesArray:self.topicModel.B_ImageArray parameterOfimages:@"files" parametersDict:nil compressionRatio:0.7 succeedBlock:^(NSDictionary *dict) {
        HXLog(@"data  %@", dict);
        if ([dict[@"code"] isEqualToString:@"20010"]) {
            [weSelf submitData:dict[@"values"]];
        } else {
            [KeyWindow makeToast:dict[@"message"]];
        }
    } failedBlock:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
    
    
    
    
    
    
    
    
    
}

/**
 TODO:上传数据

 @param array 返回的图片的list
 */
- (void) submitData:(NSArray *) array {
    NSMutableDictionary * dictionary = [NSMutableDictionary dictionary];
    
    if (ISNULL(self.topicModel.B_TopicTitle)) {
        [KeyWindow makeToast:@"请输入话题标题"];
        return;
    } else {
        [dictionary setObject:self.topicModel.B_TopicTitle forKey:@"title"];
    }
    
    if (ISNULL(self.topicModel.B_TopicContent)) {
        [KeyWindow makeToast:@"请输入话题内容"];
        return;
    } else {
        [dictionary setObject:self.topicModel.B_TopicContent forKey:@"content"];
    }
    
    [dictionary setObject:getUserId() forKey:@"userId"];
    if (self.isBusiness) {
        NSMutableArray * arr = [NSMutableArray array];
        [arr removeAllObjects];
        if (ISNULL(self.topicModel.B_GoodsArray)) {
            [dictionary setObject:@[] forKey:@"goodsId"];
        } else {
            for (B_SelecetGoodslistModel * model in self.topicModel.B_GoodsArray) {
                [arr addObject:model.id];
            }
        }
        [dictionary setObject:arr forKey:@"goodsId"];
    } else {
        [dictionary setObject:@[] forKey:@"goodsId"];
    }
    [dictionary setObject:array forKey:@"picture"];
    WeakSelf(weSelf, self);
    [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/topic/addTopic" parameters:@{@"str" : [dictionary mj_JSONString]} isCache:NO succeed:^(id data) {
        HXLog(@"data  %@", data);
        if ([data[@"code"] isEqualToString:@"20005"]) {
            [weSelf dismissViewControllerAnimated:YES completion:nil];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
    
}


@end
